import Buff from '@/Buff';
import BuffUtil from '@/BuffUtil';
import ColorStr from '@/ColorStr';
import ObjectPool from '@/ObjectPool';
import PlayerUtil from '@/PlayerUtil';
import SelectUtil from '@/SelectUtil';
import SolarBuffState from '@/SolarBuffState';
import { Frame } from '@/frame';
import { Trigger } from '@/trigger';
import ArrayCommon from 'code/Core/Common/ArrayCommon';

const PlayerColors: string[] = [ColorStr.red, ColorStr.blue, ColorStr.lumber, ColorStr.purple, ColorStr.yellow, ColorStr.orange];

function formatTime(time: number) {
    let t = time / 1000;
    let h = t / 3600;
    if (h >= 1.65) {
        return R2I(h + 1) + 'h';
    }
    let m = t / 60;
    if (m >= 1.65) {
        return R2I(m + 1) + 'm';
    }
    return R2I(t * 10) / 10 + 's';
}

export default class UIBuffs {
    /** 以frame为key存储buff的数据，用于显示提示 */
    frameMapBuffData: { [id: string]: Buff } = {};
    uiPool = new ObjectPool<Frame[]>(this.poolCreator);
    poolCreator() {
        let size = 0.025;
        let art = Frame.createBackDrop().setSize(size, size).setTexture('');
        let stack = Frame.createTEXT(art.current).setSize(size, size).setAllPoints(art.current).setText('').setFont(0.01, 'fonts\\fonts.ttf');
        stack.setTextAlignment(TEXTALIGN_CENTER);
        let duration = Frame.createTEXT(art.current).setSize(size, 0.01).setPoint(FRAMEPOINT_TOPLEFT, art.current, FRAMEPOINT_TOPLEFT, 0, 0.01).setText('').setFont(0.01, 'fonts\\fonts.ttf');
        duration.setTextAlignment(TEXTALIGN_CENTER);
        stack.setOnMouseEnter(UIManager.UIBuffsInstance.showTip);
        stack.setOnMouseLeave(UIManager.UIBuffsInstance.hideTip);
        const result = [art, stack, duration];
        return result;
    }
    constructor() {
        SolarBuffState.config.showSolarBuffUI = false;
        let trigger = new Trigger();
        trigger.registerTimerEvent(0.1, true);
        trigger.addAction(this.refreshBuffUI);
    }

    showTip() {
        let h = DzGetTriggerUIEventFrame();
        let buff = UIManager.UIBuffsInstance.frameMapBuffData['f' + h];
        if (buff) {
            let 提示文本 = ColorStr.yellow + (buff.getName() ?? '') + '|n|n';
            if (buff.stackCount && buff.stackCount != 1) {
                提示文本 = 提示文本 + ColorStr.green + '层数: ' + (buff.stackCount ?? '1') + '|n';
            }
            提示文本 = 提示文本 + ColorStr.white + (buff.getUbertip() ?? '');
            let caster = buff.getCaster();
            if (caster) {
                let p = GetOwningPlayer(caster);
                if (PlayerUtil.isUser(p)) {
                    提示文本 += `|n|n来源：${PlayerColors[GetPlayerId(p)]}${GetPlayerName(p)}|r的${ColorStr.gold}${GetUnitName(caster)}`;
                }
            }
            UIManager.CommonUITip.show(提示文本);
        }
    }
    hideTip() {
        UIManager.CommonUITip.hide();
    }
    buffSort(a: Buff, b: Buff) {
        let i = S2I(a.uuid.substring(2));
        let j = S2I(b.uuid.substring(2));
        return i - j;
    }
    refreshBuffUI(this: void) {
        let 目标 = SelectUtil.getRealSelectUnit();
        if (目标 == null) {
            UIManager.UIBuffsInstance.clearBuffUI();
            return;
        }
        let 目标buff集合 = BuffUtil.getUnitBuffs(目标);
        if (目标buff集合 == null) {
            UIManager.UIBuffsInstance.clearBuffUI();
            return;
        }
        let buffs: Buff[] = ArrayCommon.table2Array(目标buff集合);
        buffs = buffs.sort(UIManager.UIBuffsInstance.buffSort);
        // 逐个显示buff
        let 池 = UIManager.UIBuffsInstance.uiPool;
        池.setAllIdleStatus(true);
        let index = 0;
        let x位置 = 0.215;
        for (let buff of buffs) {
            // 排除不显示的buff
            if (buff.buffType.class && buff.buffType.class != '基础' && buff.buffType.class != '羁绊' && buff.buffType.class != '光环') {
                continue;
            }
            // 渲染要显示的buff
            let ui组 = 池.borrowObject();
            let [图标ui, 层数ui, 持续时间ui] = ui组;
            图标ui.setVisible(true);
            图标ui.setTexture(buff.buffType.art);
            图标ui.setAbsPoint(FRAMEPOINT_BOTTOMLEFT, x位置 + index * 0.027, 0.14);
            if (buff.buffType.stackCountMax && buff.buffType.stackCountMax != 0) {
                层数ui.setText(buff.stackCount + '');
            } else {
                层数ui.setText('');
            }
            let 持续时间 = buff.buffType.class == '光环' || buff.buffType.class == '永久' ? 'N/A' : formatTime(buff.getRemainingTime());
            if (buff.buffType.dur == null) {
                持续时间 = 'N/A';
            }
            持续时间ui.setText(持续时间);
            UIManager.UIBuffsInstance.frameMapBuffData['f' + 层数ui.current] = buff;
            index++;
        }

        池.forDirtyObjects((frames) => {
            frames[0].visible = false;
        });
    }
    clearBuffUI() {
        UIManager.UIBuffsInstance.uiPool.forActiveObjects((f) => (f[0].visible = false));
    }
}
